import Vue from 'vue'
import VueRouter from 'vue-router'
import Home from '../views/Home.vue'
import Index from '../views/Index.vue'
import User from '../views/sys/User'
import Role from '../views/sys/Role'
import Menu from '../views/sys/Menu'

import axios from "../axios";
import store from '../store'

Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    name: 'Home',
    component: Home,
    children: [
        {
            path: '/index',
            name: 'Index',
            meta: {
                title: '首页'
            },
            component: Index
        },
        {
            path: '/userCenter',
            name: 'UserCenter',
            meta: {
              title: '个人中心'
            },
            component: () => import('../views/UserCenter.vue')
        }
    ]
  },
  {
    path: '/login',
    name: 'Login',
    component: () => import('../views/Login.vue')
  }
]

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})

router.beforeEach((to, from, next) => {
    //因为每次访问路由都会经过此，所以定义参数判断是否获取过
    let hasRoute = store.state.menus.hasRoute

    let token = localStorage.getItem("token")

    if (to.path == '/login') {
        next()

    } else if (!token) {
        next({path: '/login'})


    } else if(token && !hasRoute) {
        //这没有使用main.js导入的axios，即没有使用axios.js，所以需要手动添加token
        axios.get("/sys/menu/nav").then(response => {
            debugger
            //拿到menuList
            store.commit("setMenuList",response.data.menuList)

            //拿到按钮操作权限
            store.commit("setPermissionList",response.data.permissionList)

            //动态绑定路由
            let newRoutes = router.options.routes
            response.data.menuList.forEach(menu => {//系统管理
                if(menu.children){
                    menu.children.forEach(item => {//用户管理、角色管理
                        //转换成路由
                        let route = menuToRoute(item)

                        //把路由添加到路由管理中
                        if(route){
                            //添加到Home下面
                            newRoutes[0].children.push(route)
                        }
                    })
                }
            })

            console.log("newRoutes",newRoutes)
            //将新路由绑定到路由管理
            router.addRoutes(newRoutes)

            hasRoute = true
            store.commit("changeRouteStatus",hasRoute)
        })
    }


    //继续往下走，让页面不会报错
    next()
})

const menuToRoute = (menu) => {
    //为空直接返回
    if(!menu.component){
        return null
    }
    let route = {
        name: menu.name,
        path: menu.path,
        component: () => import('../views/' + menu.component + '.vue'),
        meta: {
            icon: menu.icon,
            title: menu.title
        }
    }
    return route
}

export default router
